package com.hl.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NettyClient{

    private static ExecutorService executorService= Executors.newFixedThreadPool(1);


    public static void main(String[] args) {
        client();
    }



    public static void client(){
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();

        try {
            bootstrap.group(bossGroup)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .channel(NioSocketChannel.class)

                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new ShareChannelHandler());
                            ch.pipeline().addLast(new MyNettyClientHandler());
                        }
                    });

            ChannelFuture future = bootstrap.connect("localhost", 8888).sync();
            Channel channel = future.channel();

            channel.writeAndFlush(" this client msg").sync();

            executorService.submit(new ChannelSubmitTaskRunnable(channel));

            channel.closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
        }


    };

}
